package org.lc.kcjxzj.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.lc.kcjxzj.model.Kcjxzj;
import org.lc.kcjxzj.model.Result;
import org.lc.kcjxzj.repository.KcjxzjRepository;
import org.lc.kcjxzj.repository.ResultRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import jakarta.persistence.criteria.Predicate;

@Controller
@RequestMapping("/statistics")
public class StatisticsController {

    // 创建动态查询条件
    private Specification<Result> createFilterSpec(String course, String teacher, String semester, Float minSimilarity) {
        return (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            
            if (course != null && !course.isEmpty()) {
                predicates.add(cb.or(
                    cb.like(root.get("zjA").get("course"), "%" + course + "%"),
                    cb.like(root.get("zjB").get("course"), "%" + course + "%")
                ));
            }
            
            if (teacher != null && !teacher.isEmpty()) {
                predicates.add(cb.or(
                    cb.like(root.get("zjA").get("teacher"), "%" + teacher + "%"),
                    cb.like(root.get("zjB").get("teacher"), "%" + teacher + "%")
                ));
            }
            
            // 添加学期过滤条件
            if (semester != null && !semester.isEmpty()) {
                predicates.add(cb.or(
                    cb.equal(root.get("zjA").get("xueqi"), semester),
                    cb.equal(root.get("zjB").get("xueqi"), semester)
                ));
            }
            
            if (minSimilarity != null) {
                predicates.add(cb.greaterThanOrEqualTo(root.get("zjSimilarity4"), minSimilarity));
            }
            
            return cb.and(predicates.toArray(new Predicate[0]));
        };
    }

    private final KcjxzjRepository kcjxzjRepository;
    private final ResultRepository resultRepository;
    
    public StatisticsController(KcjxzjRepository kcjxzjRepository, ResultRepository resultRepository) {
        this.kcjxzjRepository = kcjxzjRepository;
        this.resultRepository = resultRepository;
    }

    @GetMapping
    public String showStatistics(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(required = false) String course,
            @RequestParam(required = false) String teacher,
            @RequestParam(required = false) Float minSimilarity,
            Model model) {
        
        // 转换百分比为小数
        Float similarityThreshold = minSimilarity != null ? minSimilarity / 100 : null;
        
        // 构建动态查询条件
        Specification<Result> spec = createFilterSpec(course, teacher, teacher, similarityThreshold);
        
        // 获取过滤后的结果集
        List<Result> filteredResults = resultRepository.findAll(spec);
        
        // 计算总记录数基于过滤结果
        long totalPairs = filteredResults.size();
        model.addAttribute("totalPairs", totalPairs);
        
        // 获取关联的课程记录
        List<Kcjxzj> relatedRecords = kcjxzjRepository.findAllById(
            filteredResults.stream()
                .flatMap(r -> List.of(r.getZjA().getId(), r.getZjB().getId()).stream())
                .distinct()
                .collect(Collectors.toList())
        );
        
        // 基于过滤结果的统计
        int totalRecords = relatedRecords.size();
        model.addAttribute("totalRecords", totalRecords);
        
        int courseCount = (int) relatedRecords.stream()
                .map(Kcjxzj::getCourse)
                .distinct()
                .count();
        model.addAttribute("courseCount", courseCount);
        
        int teacherCount = (int) relatedRecords.stream()
                .map(Kcjxzj::getTeacher)
                .distinct()
                .count();
        model.addAttribute("teacherCount", teacherCount);
        
        Map<String, Long> semesterStats = relatedRecords.stream()
                .collect(Collectors.groupingBy(
                        Kcjxzj::getXueqi,
                        Collectors.counting()
                ));
        model.addAttribute("semesterStats", semesterStats);
        
        
        
        // 分页查询应用过滤条件
        Page<Result> pageResults = resultRepository.findAll(spec, PageRequest.of(page - 1, size));
        model.addAttribute("detailedResults", pageResults.getContent());
        model.addAttribute("page", pageResults);
        
        return "statistics";
    }
   
}
